import { ObjectId } from "mongodb";
import { ISession } from "../models/user";
import * as db from "../db";
import { stats } from "../libs/stats";

/**
 * 创建session
 * @param record 
 */
export async function createSession(record: ISession) {
  const result = await db.sessions.insertOne(record);
  if (!result.insertedId) {
    throw stats.ErrDataBaseError;
  }
}

/**
 * 查找session
 * @param sid 
 * @returns 
 */
export async function findSession(sid: string) {
  const result = await db.sessions.findOne({
    sid,
  });
  if (!result) {
    throw stats.ErrSessionNotFound;
  }
  return result;
}

/**
 * 删除某个session
 * @param sid 
 */
export async function deleteSession(sid: string) {
  const result = await db.sessions.findOneAndDelete({
    sid,
  });
  if (!result.value) {
    throw stats.ErrSessionNotFound;
  }
}

/**
 * 删除某个用户的所有session
 * @param userId 用户id
 */
export async function deleteAll(userId: ObjectId) {
  const result = await db.sessions.deleteMany({
      userId,
  });
}
